#'
#' subset a set of individuals from a population or a community
#' 
#' @aliases subset.population subset.community
#'
#' @param pop a population object
#' @param com a community object
#' @param i index of selected individuals or a logical vector with the same length with the population or community
#'
#' @usage
#' subset(pop,i)
#' pop[i,]
#' subset(com,i)
#' com[i,]
#' com[i]
#'
#' @note 
#' please note that the level information of each factors in the parent will change.
#'@examples
#' set.seed(1)
#' pop=rpopulation()
#' pop1=subset(pop,1:4)
#' pop1
#' pop[1:4,]
#' 
#' com=rcommunity()
#' subset(com,1:4)
#' com[1:4,]
#' com[1:5]
#'
#'
#' 
#' 

#' @export
subset.population=function(pop,i,j){
 pop[i,j]
}

# TODO subset population/community by a window

#' @export
`[.population` <- function(pop, i, j, drop=FALSE, ...){
  #keep attributes
  allattrs=attributes(pop)
  class(pop)="data.frame"
  
  if(!missing(i)){
    allattrs$row.names=allattrs$row.names[i]
    pop=pop[i,]
  }
  
  if(!missing(j)){
    allattrs$names=allattrs$names[j]
    pop=pop[,j,drop=drop]
    if(drop){
      if(length(j)==1)
        pop=as.numeric(pop)
      else
        pop=as.matrix(pop)
    }
    #if species, x, y no longer exist, it just an data frame
    if(!drop & any(is.na(match(c("x","y"),names(pop)))) ){
      allattrs$class="data.frame"
    }
  }

  if(!drop)
    attributes(pop)=allattrs
  
  return(pop)
  
}

#' @export
subset.community=function(com,i,j){
  com[i,j]
}

#' @export
`[.community` <- function(com, i, j, drop=FALSE, ...){
  #keep attributes
  allattrs=attributes(com)
  class(com)="data.frame"
  
  if(!missing(i)){
    allattrs$row.names=allattrs$row.names[i]
    com=com[i,]
  }
  
 if(!missing(j)){
   allattrs$names=allattrs$names[j]
   com=com[,j,drop=drop]
   #if species, x, y no longer exist, it just an data frame
   if(!drop & any(is.na(match(c("species","x","y"),names(com)))) ){
     allattrs$class="data.frame"
   }
 }
  if("species" %in% names(com)){
    com$species=as.factor(as.character(com$species))
  }
  if(!drop)
    attributes(com)=allattrs
  
  return(com)
}

